package com.yvan.simple;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luoyifan on 2018/7/26.
 */
@SpringBootApplication(exclude = {
        HibernateJpaAutoConfiguration.class,
        DataSourceAutoConfiguration.class
})
@EnableWebMvc
public class ServerStart {

    private static final Logger log = LoggerFactory.getLogger(ServerStart.class);
    public static String UI_PATH;
    public static String ECHO_CONSTS;
    public static boolean OPEN_BROWSER = true;

    public static void main(String[] args) throws IOException {
        SpringApplication application = new SpringApplication(ServerStart.class);
        application.setBannerMode(Banner.Mode.OFF);
        args = parseArgs(args);
        if (args == null)
            return;
        application.run(args);
    }

    @Bean
    public AppStartListener appStartListener() {
        return new AppStartListener();
    }

    private static void help(String error) {
        log.info(error);
        log.info("ys [-p port] [-no openBrowser] [path]");
    }

    private static void help() {
        help("");
    }

    private static String[] parseArgs(String[] args) throws IOException {
        Map<String, String> argMap = new LinkedHashMap<>();
        String pkey = "";
        for (String arg : args) {
            arg = arg.trim();
            if (arg.length() <= 0) {
                continue;
            }

            if ("-p".equals(arg)) {
                pkey = "port";
                continue;
            }
            if ("-e".equals(arg)) {
                pkey = "echo";
                continue;
            }
            if ("-no".equals(arg)) {
                OPEN_BROWSER = false;
                continue;
            }
            if ("-h".equals(arg)) {
                help();
                continue;
            }

            if ("port".equals(pkey)) {
                argMap.put("port", arg);
                pkey = "";
                continue;
            }
            if ("echo".equals(pkey)) {
                argMap.put("echo", arg);
                pkey = "";
                continue;
            }
            if (Strings.isNullOrEmpty(pkey)) {
                argMap.put("uipath", arg);
            }
        }

        //============= port ==============
        if (argMap.containsKey("port")) {
            argMap.put("server.port", argMap.get("port"));
            log.info("port = " + argMap.get("port"));
            argMap.remove("port");
        }

        //============= uipath ==============
        String uipath;
        if (argMap.containsKey("uipath")) {
            uipath = argMap.get("uipath");
        } else {
            uipath = System.getProperty("user.dir");
        }
        uipath = new File(uipath).getCanonicalPath();
        uipath = Joiner.on("/").join(
                Splitter.on("/").split(
                        Joiner.on("/").join(
                                Splitter.on("\\").omitEmptyStrings().split(uipath)
                        ))
        );
        if (!uipath.endsWith("/")) {
            uipath = uipath + "/";
        }
        File f = new File(uipath);
        if (!f.exists()) {
            help(uipath + " not exists!");
            return null;
        }
        if (!f.isDirectory()) {
            help(uipath + " not directory!");
            return null;
        }
        log.info("uipath = " + uipath);
        UI_PATH = "file:" + uipath;

        //============= echo ==============
        if (argMap.containsKey("echo")) {
            ECHO_CONSTS = argMap.get("echo");
            argMap.remove("echo");
        } else {
            ECHO_CONSTS = "ALL";
        }

        //argMap.put("spring.resources.static-locations", uipath);
        //argMap.put("spring.freemarker.template-loader-path", uipath);

        List<String> argList = new ArrayList<>();
        for (Map.Entry<String, String> entry : argMap.entrySet()) {
            final String i = "--" + entry.getKey() + "=" + entry.getValue();
            argList.add(i);
        }
        String[] r = new String[argList.size()];
        argList.toArray(r);
        return r;
    }
}

